﻿Imports System.IO
Imports SAUpdater.Utils
Imports System.Text
Imports SACommon
Imports SASettings
Imports System.ComponentModel

<Browsable(False)>
Public Class ucVersion
    Dim mVersionFile As VersionFile
    Dim mVersion As VersionItem
    Dim mUpdateFileList As UpdateFile
    Private mAppSettings As AppSettings

    Private Sub ucVersion_Load(sender As Object, e As EventArgs) Handles Me.Load
        Messenger.SendMessage(Messenger.MessageType.UpdateStart, "", True)

        mAppSettings = New AppSettings
        gApp.SetAppVariables()

        lblVersionHeader.Text = "Versions: " & gUDApp.SelectedApp.ApplicationTitle
        lblInstallerVersion.Text = gUDApp.SelectedApp.InstallerVersion
        gVersion.SelectedVersionID = 0

        'Define File Groups
        lvwAppFiles.Columns(0).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwAppFiles.Columns(1).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwAppFiles.Columns(2).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

        lvwVersionFiles.Columns(0).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwVersionFiles.Columns(1).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwVersionFiles.Columns(2).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

        m_Extensions = New Dictionary(Of [String], [String])()
        Extensions.Add("exe", "Executable(s)")
        Extensions.Add("dll", "Assemblies or dll(s)")
        Extensions.Add("oth", "Other Included Files(s)")
        Extensions.Add("ref", "Reference Files(s)")

        For Each kvp As KeyValuePair(Of [String], [String]) In Extensions
            lvwAppFiles.Groups.Add(kvp.Key, kvp.Value)
            lvwVersionFiles.Groups.Add(kvp.Key, kvp.Value)
        Next

        'Define Setting froups
        lvwSettings.Columns(0).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwSettings.Columns(1).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
        lvwSettings.Columns(2).AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)

        m_Extensions = New Dictionary(Of [String], [String])()
        Extensions.Add("yes", "Active")
        Extensions.Add("no", "Deleted")

        For Each kvp As KeyValuePair(Of [String], [String]) In Extensions
            lvwSettings.Groups.Add(kvp.Key, kvp.Value)
        Next

        ResetFields()
        LoadVersions()
        LoadAppFiles()
        LoadSettings()

        Messenger.SendMessage(Messenger.MessageType.UpdateEnd, "", True)
    End Sub

#Region "Properties"
    Public ReadOnly Property Extensions() As Dictionary(Of [String], [String])
        Get
            Return m_Extensions
        End Get
    End Property
    Private m_Extensions As Dictionary(Of [String], [String])
#End Region
#Region "General Loading"
    Sub LoadVersions()
        Dim itm As ListViewItem
        'Reset menu
        lvwVersions.Groups.Clear()
        lvwVersions.Items.Clear()
        'Add items
        Dim a = (From x In gVersion.VersionList Order By x.VersionNumber Descending).ToList
        For Each item In a
            itm = New ListViewItem With {.ImageIndex = ReturnVersionIcon(item.VersionStatus), .Text = item.VersionNumber, .Tag = item.VersionID}
            lvwVersions.Items.Add(itm)
        Next
    End Sub
    Sub LoadAppFiles()
        Dim tVersion As String
        Dim myFileVersionInfo As FileVersionInfo
        UseWaitCursor = True
        lvwAppFiles.Items.Clear()

        lvwAppFiles.BeginUpdate()

        Dim tString As String

        For Each ap In gAppFile.AppFileList

            If ap.IncludeStatus = True Then
                If File.Exists(ap.Fullname) = True Then
                    tString = "Available"
                Else
                    tString = "Missing"
                End If

                Try
                    myFileVersionInfo = FileVersionInfo.GetVersionInfo(ap.Fullname)
                    tVersion = myFileVersionInfo.FileVersion
                Catch ex As Exception
                    tVersion = ""
                End Try

                Dim strExtension As [String] = Path.GetExtension(ap.Fullname).ToLower().TrimStart("."c)
                Dim lvi As ListViewItem = lvwAppFiles.Items.Add(ap.Fullname)

                lvi.SubItems.Add(tVersion)
                lvi.SubItems.Add(tString)

                lvi.Tag = ap.FileID
                lvi.Group = lvwAppFiles.Groups(Utils.ReturnGroupIndicator(ap.ReferenceFile, strExtension))
            End If
        Next

        lvwAppFiles.Columns(0).Width = -1
        lvwAppFiles.Columns(1).Width = -2
        lvwAppFiles.Columns(2).Width = -2

        lvwAppFiles.EndUpdate()

        UseWaitCursor = False
    End Sub
    Sub LoadVersionFiles()
        Dim tAppFileItem As AppFileItem
        Dim tFilename As String
        Dim tStatus As SAEventArgs.StatusCodes

        UseWaitCursor = True
        lvwVersionFiles.Items.Clear()

        lvwVersionFiles.BeginUpdate()

        mVersion = gVersion.SelectedVersion

        For Each ap In mVersion.VersionFiles
            tAppFileItem = gAppFile.GetAppFile(ap.FileID)

            Try
                Dim a = New FileInfo(tAppFileItem.Fullname)
                tFilename = a.Name.ToString
                ap.MD5 = Security.GenerateFileMD5(tAppFileItem.Fullname)
            Catch ex As Exception
                tFilename = ""
                ap.MD5 = ""
            End Try

            Dim strExtension As [String] = Path.GetExtension(tAppFileItem.Fullname).ToLower().TrimStart("."c)
            Dim lvi As ListViewItem = lvwVersionFiles.Items.Add(tFilename)

            lvi.SubItems.Add(ReturnDirectoryName(tAppFileItem.DirectoryID))
            lvi.SubItems.Add(UpdateOptionDescription(ap.UpdateOptionValue))

            lvi.Tag = ap.FileID
            lvi.Group = lvwVersionFiles.Groups(Utils.ReturnGroupIndicator(tAppFileItem.ReferenceFile, strExtension))
        Next

        gVersion.SelectedVersionID = gVersion.Save(mVersion)

        lvwVersionFiles.Columns(0).Width = -1
        lvwVersionFiles.Columns(1).Width = -1
        lvwVersionFiles.Columns(2).Width = -2

        lvwVersionFiles.EndUpdate()

        UseWaitCursor = False
        If gVersion.SelectedVersion.VersionFiles.Count = 0 Then
            tStatus = SAEventArgs.StatusCodes.NewItem
        Else
            If mVersion.VersionStatus = SAEventArgs.StatusCodes.Uploaded Or mVersion.VersionStatus = SAEventArgs.StatusCodes.Retired Then
                tStatus = mVersion.VersionStatus
            Else
                tStatus = SAEventArgs.StatusCodes.Defined
            End If
        End If
        SetStatusButtons(tStatus)
        UpdateVersionStatus(tStatus)
    End Sub
    Function UpdateOptionDescription(Data As UpdateOptionItem) As String
        Dim tString As String = UpdateOption.UpdateOptionDescription(Data.OptionID)
        Select Case Data.OptionID
            Case Is = UpdateOption.UpdateOptionID.UpdateIfOlderThan
                Return String.Format("{0} > {1}", tString, Data.OptionValue)
            Case Else
                Return tString
        End Select
    End Function
    Sub LoadSettings()
        Dim tMatch As Boolean
        UseWaitCursor = True
        lvwSettings.Items.Clear()

        lvwSettings.BeginUpdate()

        Dim tString As String

        For Each item In mAppSettings.SettingsList
            tMatch = True

            Dim lvi As ListViewItem = lvwSettings.Items.Add(item.ID)

            lvi.SubItems.Add(item.Description)
            lvi.SubItems.Add(item.Value)

            If item.StatusID = SAEventArgs.StatusCodes.Retired Then
                tString = "no"
            Else
                tString = "yes"
                lvi.Checked = True
            End If

            lvi.Tag = item.SettingsID
            lvi.Group = lvwSettings.Groups(tString)
        Next

        lvwSettings.Columns(0).Width = -1
        lvwSettings.Columns(1).Width = -1
        lvwSettings.Columns(2).Width = -2

        lvwSettings.EndUpdate()
        UseWaitCursor = False
    End Sub
#End Region
#Region "Process UI"
    Private Sub btnVersionAdd_Click(sender As Object, e As EventArgs) Handles btnVersionAdd.Click
        If gVersion.SelectedVersionID = 0 Then
            mVersion = New VersionItem() With {.VersionNumber = txtAppVersion.Text.Trim}
        Else
            mVersion = gVersion.SelectedVersion
            mVersion.VersionNumber = txtAppVersion.Text.Trim
            mVersion.DateTimePublished = ""
            mVersion.VersionNotes = Compression.DeflateString(rtbNotes.Rtf)
        End If
        gVersion.SelectedVersionID = gVersion.Save(mVersion)
        ResetFields()
        LoadVersions()
    End Sub
    Private Sub btnAddFiles_Click(sender As Object, e As EventArgs) Handles btnAddFiles.Click
        Messenger.SendMessage(Messenger.MessageType.UpdateStart, "", True)
        Dim tFileID As Integer
        For z As Int32 = 0 To lvwAppFiles.Items.Count - 1
            tFileID = CInt(lvwAppFiles.Items(z).Tag)
            If lvwAppFiles.Items(z).Checked = True Then AddVersionFile(tFileID, lvwAppFiles.Items(z).SubItems(1).Text)
            lvwAppFiles.Items(z).Checked = False
        Next
        gVersion.SelectedVersionID = gVersion.Save(mVersion)
        LoadVersionFiles()
        Messenger.SendMessage(Messenger.MessageType.UpdateEnd, "", True)
    End Sub
    Private Sub lvwVersions_Click(sender As Object, e As EventArgs) Handles lvwVersions.Click
        If lvwVersions.SelectedItems.Count > 0 Then
            gVersion.SelectedVersionID = CInt(lvwVersions.SelectedItems(0).Tag)
            mVersion = gVersion.SelectedVersion
            txtAppVersion.Text = mVersion.VersionNumber
            lblCreatedDate.Text = DateFunctions.GetDateTimeFromString(mVersion.DateTimeCreated).ToString("F")
            If mVersion.DateTimePublished = "" Then lblPublishedDate.Text = "" Else lblPublishedDate.Text = DateFunctions.GetDateTimeFromString(mVersion.DateTimePublished).ToString("F")
            chkBeta.Checked = mVersion.IsBeta
            rtbNotes.Rtf = Compression.InflateString(mVersion.VersionNotes)
            LoadVersionFiles()
            btnVersionAdd.Text = "Update"
        End If
    End Sub
    Private Sub btnVersionCancel_Click(sender As Object, e As EventArgs) Handles btnVersionCancel.Click
        ResetFields()
    End Sub
    Private Sub btnSelAll_Click(sender As Object, e As EventArgs) Handles btnSelAll.Click
        For z As Int32 = 0 To lvwAppFiles.Items.Count - 1
            lvwAppFiles.Items(z).Checked = True
        Next
    End Sub
    Private Sub btnClearFiles_Click(sender As Object, e As EventArgs) Handles btnClearFiles.Click
        For z As Int32 = 0 To lvwVersionFiles.Items.Count - 1
            mVersion.VersionFiles = New List(Of VersionFile)
        Next
        LoadVersionFiles()
    End Sub
    Private Sub btnPublish_Click(sender As Object, e As EventArgs) Handles btnPublish.Click
        PublishData()
    End Sub
    Private Sub btnStopAll_Click(sender As Object, e As EventArgs) Handles btnStopAll.Click
        StopAllUpdates()
    End Sub
    Private Sub btnClearAll_Click(sender As Object, e As EventArgs) Handles btnClearAll.Click
        rtbNotes.Text = ""
    End Sub
    Private Sub btnUpdateOptions_Click(sender As Object, e As EventArgs) Handles btnUpdateOptions.Click
        Dim f As New frmUpdateOptions
        If f.ShowDialog(Me) = DialogResult.OK Then
            Dim uo As New UpdateOptionItem With {.OptionID = f.UpdateOptionID, .OptionValue = f.UpdateOptionValue}
            For z As Int32 = 0 To lvwAppFiles.Items.Count - 1
                If lvwVersionFiles.Items(z).Checked = True Then
                    For Each ap In mVersion.VersionFiles
                        If ap.FileID = CInt(lvwVersionFiles.Items(z).Tag) Then
                            ap.UpdateOptionValue = uo
                        End If
                    Next
                End If
            Next
            gVersion.SelectedVersionID = gVersion.Save(mVersion)
            LoadVersionFiles()
        End If
    End Sub
#End Region
#Region "General Functions"
    Sub ResetFields()
        gVersion.SelectedVersionID = 0
        txtAppVersion.Text = ""
        btnVersionAdd.Text = "Add"
        lblCreatedDate.Text = ""
        lblPublishedDate.Text = ""
        lblInstallerVersion.Text = gUDApp.SelectedApp.InstallerVersion
        btnPublish.Enabled = False
        btnAddFiles.Enabled = False
        btnClearFiles.Enabled = False
        lvwVersionFiles.Items.Clear()
    End Sub
    Sub AddVersionFile(FileID As Integer, Version As String)
        Try
            mVersionFile = (From x In mVersion.VersionFiles Where x.FileID = FileID).First
            mVersion.VersionFiles.Remove(mVersionFile)
        Catch
            mVersionFile = New VersionFile() With {.FileID = FileID,
                                                   .Uploaded = False,
                                                   .CompressedMD5 = "",
                                                   .MD5 = ""}
        End Try
        mVersionFile.Version = Version
        mVersion.VersionFiles.Add(mVersionFile)
    End Sub
    Function ReturnDirectoryName(SelectedDirectoryID As Integer) As String
        Try
            Return (From x In gUDApp.SelectedApp.DirectoryList Where x.DirectoryID = SelectedDirectoryID).First.Directory
        Catch ex As Exception
            Return ""
        End Try
    End Function
    Function ReturnVersionIcon(VersionStatus As SAEventArgs.StatusCodes) As Integer
        If VersionStatus = SAEventArgs.StatusCodes.NewItem Then Return VersionImageIndex.NewApp
        If VersionStatus = SAEventArgs.StatusCodes.Defined Then Return VersionImageIndex.Defined
        If VersionStatus = SAEventArgs.StatusCodes.Uploaded Then Return VersionImageIndex.Uploaded
        Return VersionImageIndex.Retired
    End Function
    Sub UpdateVersionStatus(VersionStatus As SAEventArgs.StatusCodes)
        If VersionStatus = SAEventArgs.StatusCodes.Uploaded Then
            mVersion.DateTimePublished = DateFunctions.GetDateTimeString(Now())
            lblPublishedDate.Text = DateFunctions.GetDateTimeFromString(mVersion.DateTimePublished).ToString("F")
        End If
        If mVersion.VersionStatus <> VersionStatus Then
            mVersion.VersionStatus = VersionStatus
            gVersion.Save(mVersion)
            LoadVersions()
        End If

        gUDApp.NewVersionStatus = VersionStatus
        gUDApp.Save(gUDApp.SelectedApp)
    End Sub
    Sub SetStatusButtons(VersionStatus As SAEventArgs.StatusCodes)
        If VersionStatus = SAEventArgs.StatusCodes.NewItem Or VersionStatus = SAEventArgs.StatusCodes.Defined Then
            btnAddFiles.Enabled = True
            btnClearFiles.Enabled = True
        End If
        If VersionStatus = SAEventArgs.StatusCodes.Defined Then
            btnPublish.Enabled = True
        End If
        If VersionStatus = SAEventArgs.StatusCodes.Uploaded Then
            btnPublish.Enabled = True
        End If
        btnAddFiles.Enabled = True
        btnClearFiles.Enabled = True
        btnUpdateOptions.Enabled = True
    End Sub
#End Region
#Region "Publish Routines"
    Sub PublishData()
        If mVersion.VersionFiles.Count = 0 Then Exit Sub

        Messenger.SendMessage(Messenger.MessageType.UpdateStart, "", True)

        Dim tAppFileItem As AppFileItem
        Dim tFilename As String
        Dim tOriginFilename As String
        Dim tDestinationFilename As String

        Dim counter As Integer = 1

        Dim tDoArchive As Boolean = False
        Dim tDoUpload As Boolean = False
        Dim tDoPublish As Boolean = False

        Dim f = New frmPublish
        f.ShowDialog(Me)
        Dim result As String = f.Selection
        If InStr(result, "1*") > 0 Then tDoArchive = True
        If InStr(result, "2*") > 0 Then tDoUpload = True
        If InStr(result, "3*") > 0 Then tDoPublish = True

        'Consists as these steps
        Messenger.SendMessage(Messenger.MessageType.WaitformOpen, "", True)

        '1. Create Version Data Directory
        Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Preparing folders ...", True)

        Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, "Preparing folders ...", True)

        If Directory.Exists(gApp.DataVersionDirectory) = False Then Directory.CreateDirectory(gApp.DataVersionDirectory)
        If Directory.Exists(gApp.ArchiveDataVersionDirectory) = False Then Directory.CreateDirectory(gApp.ArchiveDataVersionDirectory)
        If Directory.Exists(gApp.TempDirectory) = True Then Directory.Delete(gApp.TempDirectory, True)
        If Directory.Exists(gApp.TempDirectory) = False Then Directory.CreateDirectory(gApp.TempDirectory)

        '2. Copy files to Version Data directory, Archive file and Copy to Archive Version Data directory
        If tDoArchive = True Then
            For Each item In mVersion.VersionFiles
                tAppFileItem = gAppFile.GetAppFile(item.FileID)
                Messenger.SendMessage(Messenger.MessageType.GeneralMessage, String.Format("Preparing: {0} ({1}%)", tAppFileItem.Fullname, CInt(counter / mVersion.VersionFiles.Count * 100)), True)
                Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, String.Format("Preparing: {0} ({1}%)", tAppFileItem.Fullname, CInt(counter / mVersion.VersionFiles.Count * 100)), True)

                tFilename = New FileInfo(tAppFileItem.Fullname).Name

                tOriginFilename = tAppFileItem.Fullname
                item.MD5 = Security.GenerateFileMD5(tAppFileItem.Fullname)

                'First delete the archive file if it exists
                tDestinationFilename = gApp.DataVersionDirectory & tFilename
                File.Delete(tDestinationFilename)
                Application.DoEvents()
                Do
                    Application.DoEvents()
                Loop Until File.Exists(tDestinationFilename) = False
                File.Copy(tOriginFilename, tDestinationFilename)

                'Copy the same file to .TMP
                'First delete if it already exists and then copy
                tDestinationFilename = gApp.TempDirectory & tFilename
                File.Delete(tDestinationFilename)
                Application.DoEvents()
                Do
                    Application.DoEvents()
                Loop Until File.Exists(tDestinationFilename) = False
                File.Copy(tOriginFilename, tDestinationFilename)

                'Delete the archive and create a new one
                tDestinationFilename = String.Format("{0}{1}.ZIP", gApp.ArchiveDataVersionDirectory, tAppFileItem.UniqueFilename)
                File.Delete(tDestinationFilename)
                Application.DoEvents()
                Do
                    Application.DoEvents()
                Loop Until File.Exists(tDestinationFilename) = False
                'This is a workaround to make Sharpcompress LZMA work
                'Create the zip
                item.CompressedMD5 = ArchiveFile(tDestinationFilename, True)

                File.Delete(gApp.TempDirectory & tFilename)
                Application.DoEvents()
                Do
                    Application.DoEvents()
                Loop Until File.Exists(gApp.TempDirectory & tFilename) = False

                item.Uploaded = False
                counter += 1
            Next
        End If
        gVersion.SelectedVersionID = gVersion.Save(mVersion)

        '3. Publish the files to the FTP File update directory
        counter = 1
        If tDoUpload = True Then
            For Each item In mVersion.VersionFiles
                tAppFileItem = gAppFile.GetAppFile(item.FileID)
                Messenger.SendMessage(Messenger.MessageType.GeneralMessage, String.Format("Uploading: {0} ({1}%)", tAppFileItem.Fullname, CInt(counter / mVersion.VersionFiles.Count * 100)), True)
                Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, String.Format("Uploading: {0} ({1}%)", tAppFileItem.Fullname, CInt(counter / mVersion.VersionFiles.Count * 100)), True)

                tOriginFilename = String.Format("{0}{1}.zip", gApp.ArchiveDataVersionDirectory, tAppFileItem.UniqueFilename)
                tDestinationFilename = String.Format("{0}/{1}.zip", gApp.FTPFileUpdateFolder, tAppFileItem.UniqueFilename)
                Utils.DoDataUpload(tOriginFilename, tDestinationFilename)
                item.Uploaded = True
                counter += 1
            Next
        End If
        gVersion.SelectedVersionID = gVersion.Save(mVersion)

        If tDoPublish = True Then
            '4. Create the UpdateFileList
            Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Creating Update File List Master ...", True)
            Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, "Creating Update File List Master ...", True)

            CreateMasterUpdateFileList()

            '5. Create and Publish the Update File List
            CreateAndUploadFileList()
            CreateAndUploadSettings()
            CreateAndUploadNotes(mVersion.VersionNotes)
            CreateAndUploadVersion()
            UpdateVersionStatus(SAEventArgs.StatusCodes.Uploaded)
        End If

        Messenger.SendMessage(Messenger.MessageType.GeneralMessage, "Publish completed successfully ...", True)
        Messenger.SendMessage(Messenger.MessageType.WaitFormMessage, "Publish completed successfully ...", True)

        Threading.Thread.Sleep(10)

        Messenger.SendMessage(Messenger.MessageType.WaitFormClose, "", True)
        Messenger.SendMessage(Messenger.MessageType.UpdateEnd, "Publish completed successfully ...", True)
    End Sub
    Sub CreateMasterUpdateFileList()
        Dim tVersionFileList As List(Of VersionFile)
        Dim tUFile As UpdateFileItem
        Dim tAppFile As AppFileItem

        mUpdateFileList = New UpdateFile
        Dim a = (From x In gVersion.VersionList Order By x.VersionNumber Descending).ToList
        For Each item In a
            tVersionFileList = item.VersionFiles

            For Each vfile In tVersionFileList
                tAppFile = gAppFile.GetAppFile(vfile.FileID)

                If tAppFile.FileStatus = SAEventArgs.StatusCodes.Available Then
                    If mUpdateFileList.FileIDExists(vfile.FileID) = False Then
                        tUFile = New UpdateFileItem
                        tUFile.Filename = tAppFile.Filename
                        tUFile.LastVersion = item.VersionNumber
                        tUFile.CompressedMD5 = vfile.CompressedMD5
                        tUFile.UniqueFilename = tAppFile.UniqueFilename
                        tUFile.MD5 = vfile.MD5
                        tUFile.Directory = ReturnDirectoryName(tAppFile.DirectoryID)
                        tUFile.UpdateRuleOption = vfile.UpdateOptionValue.OptionID
                        tUFile.UpdateRuleValue = vfile.UpdateOptionValue.OptionValue
                        tUFile.Shortcut = tAppFile.CreateShortCut
                        mUpdateFileList.Add(vfile.FileID, tUFile)
                    End If
                End If
            Next
        Next
    End Sub
    Function CreateAndUploadFileList() As SAEventArgs
        'Build the "Update Detail" jobject
        gApp.FileListFilename = String.Format("FileList_{0}.html", mVersion.VersionNumber)
        'Set  the application variables
        Do While File.Exists(gApp.UpdateVersionFileListFile)
            File.Delete(gApp.UpdateVersionFileListFile)
            Application.DoEvents()
        Loop
        Using sf As New StripeFile
            For Each items In mUpdateFileList.UpdateFileList
                sf.Add(items.Value.Filename)
                sf.Add(items.Value.Directory)
                sf.Add(items.Value.MD5)
                sf.Add(items.Value.CompressedMD5)
                sf.Add(items.Value.LastVersion)
                sf.Add(items.Value.UniqueFilename)
                sf.Add(items.Value.UpdateRuleOption)
                sf.Add(items.Value.UpdateRuleValue)
                sf.Add(CInt(items.Value.Shortcut).ToString)
                sf.AddLine()
            Next
            sf.SaveFile(gApp.UpdateVersionFileListFile, True)
        End Using

        Utils.DoDataUpload(gApp.UpdateVersionFileListFile, gApp.FTPUpdateVersionFileListFile)
        Return New SAEventArgs("", SAEventArgs.Results.Success)
    End Function
    Function CreateAndUploadSettings() As SAEventArgs
        'Build the "Update Detail" jobject
        gApp.SettingsFilename = String.Format("Settings_{0}.html", mVersion.VersionNumber)

        'Set  the application variables
        Do While File.Exists(gApp.UpdateVersionFileSettingsFile)
            File.Delete(gApp.UpdateVersionFileSettingsFile)
            Application.DoEvents()
        Loop

        Dim mSettings As New Settings(gApp.UpdateVersionFileSettingsFile)
        For Each items In mAppSettings.SettingsList
            mSettings.Add(items.ID, items.Value)
        Next
        mSettings.SaveFile()

        Utils.DoDataUpload(gApp.UpdateVersionFileSettingsFile, gApp.FTPUpdateVersionFileSettingsFile)

        Return New SAEventArgs("", SAEventArgs.Results.Success)
    End Function
    Function CreateAndUploadNotes(Notes As String) As SAEventArgs
        'Build the "Update Detail" jobject
        gApp.NotesFilename = String.Format("Notes_{0}.html", mVersion.VersionNumber)

        'Set  the application variables
        Do While File.Exists(gApp.UpdateVersionFileNotesFile)
            File.Delete(gApp.UpdateVersionFileNotesFile)
            Application.DoEvents()
        Loop

        Using objWriter = New StreamWriter(gApp.UpdateVersionFileNotesFile)
            objWriter.Write(Notes)
            objWriter.Close()
        End Using

        Utils.DoDataUpload(gApp.UpdateVersionFileNotesFile, gApp.FTPUpdateVersionFileNotesFile)

        Return New SAEventArgs("", SAEventArgs.Results.Success)
    End Function
    Function itemString(ByVal b As UpdateFileItem) As String
        Dim CsvLine As New StringBuilder
        CsvLine.Append(b.Filename + "|")
        CsvLine.Append(b.Directory + "|")
        CsvLine.Append(b.MD5 + "|")
        CsvLine.Append(b.CompressedMD5 + "|")
        CsvLine.Append(b.UniqueFilename + "|")
        CsvLine.Append(b.LastVersion + "|")
        CsvLine.Append(b.UpdateRuleOption.ToString + "|")
        CsvLine.Append(b.UpdateRuleValue)
        Return CsvLine.ToString
    End Function
    Function CreateAndUploadVersion() As SAEventArgs
        Dim tString As String = ""
        If mVersion.IsBeta = True Then tString = "Beta"

        Dim verFile As New UpdateCore.UpdateVersion() With {.Allow = True,
                                                            .CoreVersion = mVersion.VersionNumber,
                                                            .CoreIsBeta = mVersion.IsBeta,
                                                            .CoreType = tString,
                                                            .InstallerVersion = gUDApp.SelectedApp.InstallerVersion,
                                                            .InstallerMD5 = gUDApp.SelectedApp.InstallerMD5,
                                                            .HelpVersion = "", .HelpMD5 = ""}
        verFile.WriteVersionFile(gApp.UpdateVersionFile)

        Utils.DoDataUpload(gApp.UpdateVersionFile, gApp.FTPUpdateVersionFile)
        Return New SAEventArgs("", SAEventArgs.Results.Success)
    End Function
#End Region
End Class
